<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\TenantProduct\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Tenant\Contract\TenantMenuPackageContract;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\TenantProduct\Contract\TenantProductSkuContract;

/**
 * 套餐管理-修改.
 *
 * Class UpdateLogic
 */
class UpdateLogic
{
    /**
     * @Inject
     * @var TenantProductSkuContract
     */
    protected $tenantProductSkuService;

    /**
     * @Inject
     * @var TenantMenuPackageContract
     */
    protected $tenantMenuPackageService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @param array $params 请求参数
     * @return array 响应数组
     */
    public function handle(array $params): array
    {
        if ($params['marketPrice'] < $params['price']) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '套餐原价不能小于套餐现价');
        }
        // 数据操作
        Db::beginTransaction();
        try {
            // 修改商品sku
            $data = [
                'price' => $params['price'],
                'market_price' => $params['marketPrice'],
                'stock' => $params['stock'],
                'audit_status' => $params['auditStatus'],
            ];
            $this->tenantProductSkuService->updateTenantProductSkuById($params['id'], $data);
            // 修改商品属性
            foreach ($params['attributes'] as $item) {
                $this->tenantProductSkuService->updateTenantProductSkuAttributeById($item['attributeId'], ['name' => $item['attributeName']]);
                $this->tenantProductSkuService->updateTenantProductSkuValueById($item['valueId'], ['value' => $item['attributeValue']]);
                // 租户菜单处理
                if ($item['attributeName'] === '套餐功能') {
                    $this->tenantMenuPackageService->updateTenantMenuPackageBySkuId($params['id'], ['menu_id' => $item['attributeValue']]);
                }
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '套餐修改失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '套餐修改失败');
        }

        return [];
    }
}
